package com.fast.admin.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.fast.admin.entity.sys.Role;
import com.fast.admin.entity.sys.UserRole;
import com.fast.admin.mapper.sys.IRoleMapper;
import com.fast.admin.service.sys.IRoleService;
import com.fast.admin.service.sys.IUserRoleService;
import com.fast.admin.service.sys.IUserService;
import com.fast.common.annotation.Commit;
import com.fast.common.base.service.impl.BaseService;
import com.fast.common.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title：RoleService
 * @author：ylc
 * @date：2018/8/1 16:15
 * @version：1.0
 **/
@Service
public class RoleService extends BaseService<IRoleMapper, Role> implements IRoleService {

    @Autowired
    private IUserRoleService userRoleService;

    @Override
    @Commit
    public void addOrUpdate(Role role) {

        if (CommonUtil.properIsNULL(role.getId())) {
            Role temp = findByCode(role.getCode());
            if (CommonUtil.isEmpty(temp)){
                role.setStatus(1);
                super.insert(role);
            }else {
                throw new ApiException("["+role.getCode() + "]" + "数据已存在相同的");
            }
            super.updateById(role);
        }

    }

    @Override
    public List<Role> selectByUserId(Long userId) {
        List<UserRole> userRoleList = userRoleService.selectByUserId(userId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
        return super.selectList(wrapper);
    }

    private Role findByCode(String code){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("code", code);
        return super.selectOne(queryWrapper);
    }
}
